<template>
  <div class="home">
    <!--  导航开始 -->
    <commonHeader
      :title="title"
      :subtitle="subtitle"
      @goBack="goBack()"
      @goSubtitle="goSubtitle()">
    </commonHeader>
    <!--    内容-->
    <div class="content">
      <!--      背景图-->
      <div class="topBgPic">
        <!--        视频-->
        <div v-if="playerOptions.sources[0].src" class="videoContainer">
          <video-player  class="video-player vjs-custom-skin"
                         ref="videoPlayer"
                         style="margin-bottom:0.2rem"
                         :playsinline="true"
                         :options="playerOptions"
                         @pause="onPlayerPause($event)"
                         @play="onPlayerPlay($event)"
                         @timeupdate="onPlayerTimeupdate($event)"
                         @ended="onPlayerEnded($event)"
          ></video-player>
        </div>
        <!--        图片-->
        <img v-else src="http://job.dayinyun.com/oldUniversityBanner.png" alt="">
      </div>
<!--      视频分类tab-->
      <div class="curriculum">

        <!--    tab切换-->
        <div class="curriculumTabs">
          <div
            class="tabItmes flex-space-center"
            :class="{'activityCurriculum':curriculumTabsIndex == index }"
            v-for="(item,index) in curriculumTabList"
            :key="index" @click="choosedTab(item,index)">
            {{ item.name }}
          </div>
        </div>
        <!--    筛选-->
        <div class="filters">
          <!--      筛选列表-->
          <tabs :tabList="filterList" @goCenter="chooseThree"></tabs>
        </div>
        <!--    课程视频列表-->
        <!--    下拉刷新-->
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list
            v-if="courseList&&courseList.length*1>0"
            v-model="loading"
            :finished="finished"
            :offset="20"
            :immediate-check="false"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <div class="courseLists">
              <div class="courseList flex-space-between">
                <div class="courseListItems" v-for="(item,index) in courseList" :key="index" @click="exportVideoUrl(item)">
                  <!--          视频-->
                  <div class="courseVideo" :class="{'activityBorder':item.checked}" :style="{backgroundImage:'url('+item.img+')'}">
                    <!--               test_status 0未通过 1已通过-->
                    <div v-if="item.test_status*1>0" class="pass flex-space-center">通过</div>
                    <div class="time">{{item.time}}</div>
                  </div>
                  <!--          内容-->
                  <div class="courseContent">
                    <!--            标题-->
                    <div :class="{'activityWord':item.checked}" class="title twoDot">
                      <!--              <span class="flex-space-center">新</span>-->
                      {{item.name}}
                    </div>
                    <!--            类型-->
<!--                    <div class="courseType flex-space-between">-->
<!--                      <div :class="{'activityWord':item.checked}" v-html="item.desc"></div>-->
<!--                      &lt;!&ndash;                  status 状态0 未观看 1已观看 2已考试通过&ndash;&gt;-->
<!--                      <div v-if="item.status*1>0">已看完</div>-->
<!--                    </div>-->
                  </div>
                </div>
              </div>
            </div>
          </van-list>
          <div class="noData flex-space-center" v-else>
            敬请期待！
          </div>
        </van-pull-refresh>
      </div>
    </div>
    <!--    弹框-->
    <van-popup v-model="filterListShow" round position="bottom" :style="{ height: '50%' }">
      <van-tree-select
        :items="filterThreeList"
        :active-id.sync="activeId"
        :main-active-index.sync="activeIndex"
        @click-item="choosedThreeItem"
      />
    </van-popup>
  </div>
</template>

<script>
  import commonHeader from "../../components/common/commonHeader.vue"
  import tabs from '../../components/tabs'
  import {setStore,getStore} from "../../commonUtil/mUtils";
  import {GETLESSONCATEONE, GETLESSONCATETWO, GETLESSONCATETHREE, GETLESSONlIST} from "../../apis/expertClass";
  export default {
    name:"home",
    components:{
      commonHeader,
      tabs
    },
    data() {
      return {
        title:"视频专家课",
        subtitle:"专家认证",
        examinationShow:false,//参加考试按钮
        curriculumTabList: [],//学历课程一级分类
        curriculumTabsIndex:0,//学历课程一级分类下标
        filterList:[],//筛选列表
        courseList:[],//课程列表
        // 筛选弹框配置
        filterListShow:false,//筛选弹框
        filterThreeList:[],//三级筛选列表
        activeId: 0,//三级分类选中的id
        activeIndex: 0,//三级分类选中的下标
        // 上拉加载下拉刷新配置
        loading: false,//
        finished: false,//上拉加载完毕
        refreshing: false,//下拉刷新
        page:1,//分页页数
        pageSize:10,//每页数据
        videoMsg:{},//视频
        isVideoPlay:false,//视频是否播放
        // 视频配置
        playerOptions: {
          // videojs options
          width:690,
          height:210,
          muted: false,
          language: 'zh-CN',
          playbackRates: [0.7, 1.0, 1.5, 2.0],
          aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
          sources: [{
            // type: 'application/x-mpegURL',
            type: "video/mp4",
            src:"",
          }],
          poster: "/static/images/author.jpg",
          controlBar: {
            timeDivider: true,
            durationDisplay: true,
            remainingTimeDisplay: false,
            fullscreenToggle: true  //全屏按钮
          }
        }
      }
    },
    mounted() {
      // 把路径里面的token 存起来
      // let token = this.$route.query.token?this.$route.query.token:''
      // if(getStore('token')!='undefined'){
      //   setStore('token',token);
      // }
      this.$loading()
      // 获取一级分类列表
      this.getLessonCateOne()
    },
    methods:{
      // 返回
      goBack(){
        // 返回APP
        if (this.$systemInfo() === "android") {
          window.android.closeCurrentPage();
        } else if (this.$systemInfo() === "ios") {
          window.webkit.messageHandlers.closeCurrentPage.postMessage(null);
        }
      },
      // 专家认证 - 跳到专家认证
      goSubtitle(){
        let url = "https://fexpert.hongjitimes.com/certification"
        window.location.href = url
      },
      // 初始化下拉加载
      loadingInit(){
        //清空课程列表 下拉加载初始化
        this.courseList = [];//课程列表
        this.loading = false;
        this.finished = false;
        this.refreshing =false;
        this.page = 1;
        this.activeId = 0;//三级分类选中的id
        // this.$loading();//加载中
      },
      // 切换tab 选择一级分类
      choosedTab(item,index){
        this.curriculumTabsIndex = index;//当前选中的一级分类tab下标
        //清空课程列表 下拉加载初始化
        this.loadingInit();
        // 二级分类列表
        this.getLessonCateTwo(item.cate_id)
      },
      // 点击二级分类筛选列表
      chooseThree(item){
        if(item.guid*1==0){
          // 初始化
          this.loadingInit()
          // 点击全部 获取全部视频列表
          this.getLessonList()
        }else{
          // 初始化
          this.loadingInit()
          // 获取三级分类
          this.getLessonCateThree(item)
        }
      },
      // 选中3级分类
      choosedThreeItem(item){
        this.filterListShow = false;//弹框隐藏
        // this.$loading()
        this.getLessonList(this.activeId);//筛选获取课程列表
      },
      // ------------------------视频相关开始-------------------
      // 判断用户是什么网
      getNetworkType() {
        var ua = navigator.userAgent;
        var networkStr = ua.match(/NetType\/\w+/) ? ua.match(/NetType\/\w+/)[0] : 'NetType/other';
        networkStr = networkStr.toLowerCase().replace('nettype/', '');
        var networkType;
        switch(networkStr) {
          case 'wifi':
            networkType = 'wifi';
            break;
          case '4g':
            networkType = '4g';
            break;
          case '3g':
            networkType = '3g';
            break;
          case '3gnet':
            networkType = '3g';
            break;
          case '2g':
            networkType = '2g';
            break;
          default:
            networkType = 'other';
        }
        return networkType
      },
      // 导出视频路径
      exportVideoUrl(item){
        // 列表加默认不选中值
        this.courseList.map((item,index) => {
          this.$set(item,'checked',false)
        })
        // 当前点击的选中
        item.checked = true;
        // 导出视频
        this.$nextTick(()=>{
          // 切换的时候视频初始化
          this.isVideoPlay = false;//视频是否播放
          this.playerOptions.sources[0].src =  '';//视频路径
          this.playerOptions.poster = '';//默认封面图
          this.playerOptions.sources[0].src =  item.url;//视频路径
          this.playerOptions.sources[0].type = 'video/mp4';//视频类型
          this.playerOptions.poster = item.img;//默认封面图
          this.videoMsg = item;
        })
      },
      // listen event
      onPlayerPlay(player) {
        // 判断用户当前是否是wifi
        let networkType =  this.getNetworkType();
        if(networkType!='wifi'){
          this.$toast("当前使用的是非wifi - 请注意流量消耗")
        }
        // 没有播放 累加一次观看课程记录

        this.isVideoPlay = true;

      },
      // 暂停播放
      onPlayerPause(player) {
        console.log('player pause!', player)
      },
      // ...player event
      onPlayerTimeupdate(player){
        var currentTime,//播放时长
          duration,//总时长
          percentage;//百分数
        currentTime = player.cache_.currentTime
        duration = player.cache_.duration
        percentage = parseInt((currentTime*100/duration*100)/100)
        // 考试按钮是否显示
        this.examinationShow = percentage*1>=50?true:false
      },
      // 视频播放完成
      onPlayerEnded(){
        this.isVideoPlay = false;
      },
      // ----------------------------视频相关结束----------------------
      //-------------------------- 接口开始 --------------------
      // 获取课程一级分类
      getLessonCateOne(){
        let getLessonCateOne = GETLESSONCATEONE
        getLessonCateOne().then(res => {
          if(res.data.code*1===200){
            this.curriculumTabList = res.data.data;//一级分类
            // 获取二级分类列表
            this.filterList = [];//二级分类列表
            this.getLessonCateTwo(this.curriculumTabList[0].cate_id)
          } else {
            this.$toast(res.data.message);
          }
        }).catch(error => {
          console.log(error)
        })
      },
      // 获取课程二级分类
      getLessonCateTwo(cate_id){
        this.filterList = [];//二级分类列表
        let getLessonCateTwo = GETLESSONCATETWO
        let params = {
          cate_id : cate_id
        }
        getLessonCateTwo(params).then( res => {
          if(res.data.code*1===200){
            this.$nextTick(() => {
              this.filterList = res.data.data;//筛选列表
              var totalObj = {
                cate_id:0,
                name:"全部",
                level:2,
              }
              this.filterList.unshift(totalObj)
              this.filterList.forEach((item,index)=>{
                if(!item.guid){
                  this.$set(item,'guid',index)
                }
              })//tab列表

              // 获取课程列表
              this.getLessonList()
            })
          } else {
            this.$toast(res.data.message);
          }
        }).catch(error => {
          console.log(error)
        })
      },
      // 获取课程三级分类
      getLessonCateThree(item){
        this.filterThreeList = [];//清空三级分类列表
        let getLessonCateThree = GETLESSONCATETHREE
        let params = {
          cate_id:item.cate_id
        }
        getLessonCateThree(params).then( res => {
          if(res.data.code*1===200){
            // 给三级列表赋值
            let threeList = []
            let threeObj = {}
            let newThreeList = []
            threeList = res.data.data
            threeList.forEach((item,index) => {
              threeObj = {
                text:item.name,
                id:item.cate_id
              }
              newThreeList.push(threeObj)
            })
            this.filterThreeList = [
              {
                text:item.name,
                children:newThreeList
              }
            ]

            this.filterListShow = true;//弹框显示
          } else {
            this.$toast(res.data.message);
          }
        }).catch(error => {
          console.log(error)
        })
      },
      // 获取课程列表
      getLessonList(cate_id){
        let getLessonList = GETLESSONlIST
        let params = {
          cate_id:cate_id&&cate_id*1>0?cate_id:0,//三级分类ID 0全部课程 1对应分类id
          page:1,//
        }
        getLessonList(params).then( res => {
          if(res.data.code*1===200){
            // 下拉刷新
            if (this.refreshing) {
              this.courseList = [];
              this.refreshing = false;
            }
            // 关闭加载中
            this.loading = false;
            const courseList = res.data.data;//课程列表
            if(courseList == null || courseList.length*1 === 0){
              this.finished = true
              // return
            }
            if(courseList.length*1 < this.pageSize){
              this.finished = true
            }
            if(this.page*1 == 1){
              this.courseList = [];//清空数组
              this.courseList = courseList
            }else{
              this.courseList = this.courseList.concat(courseList)
            }

            // 列表加默认不选中值
            this.courseList.map((item,index) => {
              this.$set(item,'checked',false)
            })
          } else {
            this.$toast(res.data.message);
          }
        }).catch(error => {
          console.log(error)
        })
      },
      // 上拉加载
      onLoad() {
        this.page++;
        this.getLessonList(this.activeId);//获取课程列表
      },
      // 下拉刷新
      onRefresh() {
        // 清空列表数据
        this.finished = false;

        // 重新加载数据
        // 将 loading 设置为 true，表示处于加载状态
        this.loading = true;
        this.page=1;
        this.getLessonList(this.activeId);//获取课程列表
      },
      // --------------------------接口结束---------------------
    }
  }
</script>

<style lang="less" scoped>
  @import (reference) url(../../assets/less/common);
  .home{
    width:100%;
    padding:1.38rem 0rem 0.3rem 0rem;
    box-sizing: border-box;
    .content{
      width:100%;
      .topBgPic{
        width:100%;
        padding:0 0.3rem;
        box-sizing: border-box;
        .videoContainer{
          width:100%;
          height:100%;
          object-fit:fill;
          position: relative;
          /deep/.vjs-big-play-button{
            font-size: 2.5em;
            line-height: 2.3em;
            height: 2.5em;
            width: 2.2em;
            -webkit-border-radius: 2.5em;
            -moz-border-radius: 2.5em;
            border-radius: 50%;
            background-color: rgba(115,133,159,.5);
            border-width: 0.12em;
            margin-top: -1.25em;
            margin-left: -1.45em;
          }
          .examination{
            position: absolute;
            top:0.2rem;
            right:0.2rem;
            width:1.6rem;
            height:0.48rem;
            background:#FEA300;
            border:0.02rem solid rgba(255, 255, 255, 0.32);
            border-radius:0.05rem;
            font-size:@fontSize24;
            font-family:@fontFamily400;
            font-weight:@fontWeight400;
            color:@whiteColor;
            img{
              width:0.22rem;
              height:auto;
              margin-right:0.07rem;
            }
          }
        }
        img{
          width:100%;
          height: auto;
        }
      }
      /*视频*/
      .curriculum{
        width:100%;
        .curriculumTabs{
          width:100%;
          height:0.86rem;
          display: flex;
          background:#232323;
          font-size:@fontSize34;
          font-family:@fontFamily400;
          font-weight:@fontWeight500;
          color:@whiteColor;
          .tabItmes{
            width:50%;
          }
          .activityCurriculum{
            background: #FEA300;
          }
        }
        .filters{
          width: 100%;
          position: relative;
          display: flex;
          border-bottom: 0.01rem solid #313131;
        }
        .courseLists{
          width:100%;
          padding:0.3rem;
          box-sizing: border-box;
          .courseList{
            width:100%;
            flex-wrap: wrap;
            .courseListItems{
              width:3.35rem;
              margin-bottom:0.06rem;
              .courseVideo{
                width:3.35rem;
                height:2.3rem;
                background-size: 100% 100%;
                background-repeat: no-repeat;
                border-radius: 0.1rem;
                display: flex;
                flex-direction: column;
                align-items: flex-end;
                justify-content: space-between;
                padding:0.18rem;
                box-sizing: border-box;
                .time{
                  font-size: @fontSize26;
                  font-weight: @fontWeight500;
                  font-family: @fontFamily400;
                  color:@whiteColor;
                }
                .pass{
                  width:0.8rem;
                  height:0.4rem;
                  border-radius: 0.05rem;
                  background: #FEA300;
                  font-size: @fontSize24;
                  font-weight: @fontWeight400;
                  font-family: @fontFamily400;
                  color:@whiteColor;
                }
              }
              .activityBorder{
                border-left:0.06rem solid #FEA300;
              }
              .courseContent{
                width:3.35rem;
                padding: 0.34rem 0;
                .title{
                  width:3.35rem;
                  height:0.96rem;
                  font-size: @fontSize34;
                  font-weight: @fontWeight600;
                  font-family: @fontFamily400;
                  color:@whiteColor;
                  span{
                    width:0.3rem;
                    height: 0.3rem;
                    border-radius: 0.05rem;
                    background: #FEA300;
                    font-size: @fontSize24;
                    font-weight: @fontWeight500;
                    font-family: @fontFamily400;
                    color:@whiteColor;
                    margin-right:0.1rem;
                    padding:0.04rem;
                    box-sizing: border-box;
                  }
                }
                .courseType{
                  font-size: @fontSize28;
                  font-weight: @fontWeight400;
                  font-family: @fontFamily400;
                  color:rgba(255,255,255,0.8);
                  margin-top: 0.1rem;
                }
                .activityWord{
                  color:#FEA300;
                }
              }
            }
          }
        }
        .noData{
          width:100%;
          height: 4rem;
          font-size: @fontSize34;
          font-family: @fontFamily500;
          font-weight: @fontWeight400;
          color:@whiteColor;
        }
      }
    }
  }
</style>
